﻿using Corina.Datamodel.Entities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace Corina.DataContext.Service
{
    public class NationalStandardService : ServiceBase
    {
        public DataTable GetAllItems(string connectionString, string key, int index, int size, ref int count)
        {
            List<SqlParameter> paras = new List<SqlParameter>();
            string qstring = "SELECT * FROM ( ";
            string cstring = "SELECT COUNT(*) FROM ( ";
            StringBuilder builder = new StringBuilder();

            builder.Append("SELECT ROW_NUMBER() OVER (ORDER BY tns.Code DESC) AS ROW_NUMBER,tns.* ");
            builder.Append("  FROM t_national_standard AS tns ");
            builder.Append("WHERE 1=1 ");

            #region Conditions
            builder.Append("AND tns.Name LIKE @Key OR tns.Code LIKE @Key OR tns.DocumentName LIKE @Key OR tns.[Description] LIKE @Key ");
            paras.Add(new SqlParameter("@Key", string.Format("%{0}%", key)));


            #endregion

            builder.Append(") AS query ");

            count = DbOperator.GetCount(connectionString, string.Format("{0}{1}", cstring, builder), paras.ToArray());

            builder.Append("WHERE query.[ROW_NUMBER] BETWEEN @Index + 1 AND @Index + @Size ");
            paras.Add(new SqlParameter("@Index", (index - 1) * size));
            paras.Add(new SqlParameter("@Size", size));
            builder.Append("ORDER BY query.[ROW_NUMBER]");

            DataTable table = DbOperator.GetDataTable(connectionString, string.Format("{0}{1}", qstring, builder), paras.ToArray());
            return table;
        }

        public NationalStandardInfo GetEntityByCode(string connectionString, string code)
        {
            return DbOperator.GetEntity<NationalStandardInfo>(connectionString, new List<string>() { "Code" }, new List<object>() { code });
        }

        public bool Insert(string connectionString, NationalStandardInfo entity)
        {
            return DbOperator.UpdateEntity(connectionString, entity, Enumerations.EntityOperation.Insert);
        }
    }
}
